<template>
  <div class="add-template">
    <el-form ref="ruleForm"
             label-width="80px"
             :rules="rules"
             :model="form">
      <el-form-item label="模板名称"
                    prop="templateName">
        <el-input v-model="form.templateName"
                  placeholder="请输入模板名称"
                  style="width: 260px;"
                  @input="validateInput" />
      </el-form-item>
    </el-form>
    <div>
      <el-checkbox v-model="form.checked"
                   @change="handleSelectAll">全选</el-checkbox>
      <span class="remarks">（设置模板字段,可勾选要导出的字段、可拖拽调整顺序。）</span>
    </div>
    <div v-if="values"
         class="tab-column">
      <div v-for="(item, index) in dragColumns"
           :key="index"
           class="column_sheets">
        <span class="column_item">{{ item.name }}</span>
        <ExportFieldColumn :values="item.columns"
                           v-bind="$attrs" />
      </div>
      <!-- {{ tabs[currentTabIndex].content }} -->
    </div>
  </div>
</template>

<script>
import ExportFieldColumn from './ExportFieldColumn.vue'

export default {
  name: 'ExportAddTemplate',
  components: { ExportFieldColumn },
  props: {
    values: {
      type: Array,
      default: () => []
    },
    templateName: {
      type: String,
      default: '',
    },
    defaultValues: {
      type: Array,
      default: () => []
    }
  },
  data () {
    return {
      form: {
        templateName: ''
      },
      rules: {
        templateName: [
          { required: true, message: '请输入模板名称', trigger: 'blur' },
          { min: 1, max: 10, message: '长度不能超过10个字符', trigger: 'blur' }
        ]
      }
    }
  },
  computed: {
    dragColumns () {
      return this.$attrs.types === 'add' && this.defaultValues.length
        ? this.defaultValues
        : this.values;
    }
  },
  created () {
    const { types } = this.$attrs
    if (types === 'edit') {
      this.form.templateName = this.templateName
    }
  },
  methods: {
    submitForm () {
      return new Promise((resolve, reject) => {
        this.$refs['ruleForm'].validate((valid) => {
          if (valid) {
            resolve({ sheets: this.dragColumns, ...this.form }); // 表单验证通过，resolve Promise
          } else {
            reject(); // 表单验证失败，reject Promise
          }
        });
      });
    },
    validateInput () {
      this.form.templateName = this.form.templateName.replace(/\s/g, ''); // 移除空格
    },
    handleSelectAll (value) {
      this.$emit('checked', value)
    }
  }
}
</script>

<style lang="scss" scoped>
.add-template {
  // padding: 20px 0;
  /deep/ .el-form-item {
    margin-bottom: 15px;
  }
}
.remarks {
  padding-left: 8px;
  font-size: 12px;
  color: #999999;
}
.column_sheets {
  padding-top: 20px;
}
.column_item {
  display: block;
  padding-bottom: 10px;
}
</style>